package com.zhangqiang.git.mqttdemo.client;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;

@Component
public class ClientMQTT {
    private static final Logger log = LoggerFactory.getLogger(ClientMQTT.class);

    /**
     * 切分字符
     */
    public static final String MESSAGE_SPLIT = ",";

    @Autowired
    private MqConfig mqConfig;

    private MqttAsyncClient client = null;

    //发布客户端队列
    private static ConcurrentLinkedQueue<MqttClient> client_list = new ConcurrentLinkedQueue();

    /**
     * 项目启动时，初始订阅MQTT
     */
    @PostConstruct
    public void init()
    {
        start();
    }

    // 客户端订阅主题
    public boolean start(){
        if(!mqConfig.isRun())return false;
        try {
            if(client == null){
                // host为主机名，clientid即连接MQTT的客户端ID，一般以唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
                client = new MqttAsyncClient(mqConfig.getHost(), mqConfig.getClientid(), new MemoryPersistence());
            }
            // MQTT的连接设置
            MqttConnectOptions options = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(mqConfig.isCleanSession());
            // 设置连接的用户名
            options.setUserName(mqConfig.getUsername());
            // 设置连接的密码
            options.setPassword(mqConfig.getPassword().toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(mqConfig.getTimeout());
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(mqConfig.getKeepalive());
            // 设置自动重连
            options.setAutomaticReconnect(mqConfig.isAutomaticreconnect());
            // 设置回调
            client.setCallback(new MqttCallbackExtended() {
                // 连接断开时的回调
                public void connectionLost(Throwable cause) {
                    // 连接丢失后，一般在这里面进行重连，这里进行的重连不会订阅之前的主题，所以需要使用connectComplete方法
//                    System.out.println("服务端：连接断开，可以做重连"+cause);
                }
                // 消息发送成功回调
                public void deliveryComplete(IMqttDeliveryToken token) {
//                    System.out.println("deliveryComplete---------" + token.isComplete());
                }
                // 收到下推消息时的回调
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    log.info("主题{} 接收数据：{}", topic, new String(message.getPayload()));
                    // 在此编写消息处理逻辑

                }
                // 断开重连，主题重新订阅
                public void connectComplete(boolean reconnect, String serverURI) {
                    //重新连接成功后，进行订阅之前的主题
                    try
                    {
                        // 主题订阅
                        String[] topicFilters = mqConfig.getTopicFilters().split(MESSAGE_SPLIT);
                        int[] qos = new int[topicFilters.length];
                        for(int i=0;i<topicFilters.length;i++){
                            topicFilters[i] = mqConfig.getPrefixtheme()+topicFilters[i];
                            qos[i] = mqConfig.getQos();
                        }
                        client.subscribe(topicFilters, qos);
                    } catch(Exception me)
                    {
                        System.out.println("MQTT重新订阅失败.");
                        me.printStackTrace();
                    }
                }
            });

            //setWill方法，如果项目中需要知道客户端是否掉线可以调用该方法。设置最终端口的通知消息
            options.setWill("mqttclose", "close".getBytes(), 2, true);
            client.connect(options);
            // 主题订阅
            String[] topicFilters = mqConfig.getTopicFilters().split(",");
            int[] qos = new int[topicFilters.length];
            for(int i=0;i<topicFilters.length;i++){
                topicFilters[i] = mqConfig.getPrefixtheme()+topicFilters[i];
                qos[i] = mqConfig.getQos();
            }
            client.subscribe(topicFilters, qos);
            System.out.println("MQTT订阅初始化");
            return true;
        }catch (MqttException me){
            return false;
        }
    }

    // 发送主题消息
    public boolean publish(String topic, String dataMessage){
        MqttClient mqttClient = client_connect();
        if(mqttClient == null){
            return false;
        }
        try {
            //发布主题信息
            MqttMessage message = new MqttMessage();
            //0发送即丢弃 1意味着消息至少被传输一次 2确保了仅仅传输接收一次
            message.setQos(mqConfig.getQos());
            //true数据会永久保存,直到下一次数据覆盖
            message.setRetained(mqConfig.isRetained());
            message.setPayload(dataMessage.getBytes());
            mqttClient.publish(mqConfig.getPrefixtheme()+topic, message);
            client_list.add(mqttClient);
            log.info("主题{} 发送数据：{}",topic,dataMessage);
            return true;
        }catch (MqttException me){
            return false;
        }
    }

    /**
     *  用来连接服务器
     */
    private MqttClient client_connect() {
        MqttClient client_s = client_list.poll();
        if(client_s!=null) return client_s;
        try {
            client_s = new MqttClient(mqConfig.getHost(), "S_"+ UUID.randomUUID(), new MemoryPersistence());
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(mqConfig.getUsername());
            options.setPassword(mqConfig.getPassword().toCharArray());
            // 设置超时时间
            options.setConnectionTimeout(mqConfig.getTimeout());
            // 设置会话心跳时间
            options.setKeepAliveInterval(mqConfig.getKeepalive());
            client_s.connect(options);
        } catch (Exception e) {
            System.out.println("MQTT-发布消息客户端连接失败：=========================================");
            e.printStackTrace();
        }
        return client_s;
    }


    // 关闭连接
    public boolean close(){
        try {
            if (client.isConnected())
                client.disconnect();
            client.close();
            return true;
        } catch (MqttException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }
    }

}

